package controllers

import (
	"fmt"
	"gitee.com/falling-ts/gower/app"
	"gitee.com/falling-ts/gower/app/admin/requests"
	"gitee.com/falling-ts/gower/app/models"
	"gitee.com/falling-ts/gower/services"
	"math"
)

type AdminController struct {
	app.Controller
	resource    string
	breadcrumbs []map[string]any
}

var (
	Admin = &AdminController{
		Controller: app.Controller{},
		resource:   "/admin/system/admin",
		breadcrumbs: []map[string]any{
			{
				"name": "系统设置",
				"path": "#",
			},
			{
				"name": "员工管理",
				"path": "/admin/system/admin",
			},
		},
	}
)

// Index 获取列表页面
func (a *AdminController) Index(req *requests.AdminIndexRequest) (services.Response, error) {
	var (
		adminModels []models.AdminUser
		total       int64
	)
	query := db.GormDB()
	if req.Username != "" {
		query = query.Where("username LIKE ?", "%"+req.Username+"%")
	}
	if req.Email != "" {
		query = query.Where("email LIKE ?", "%"+req.Email+"%")
	}
	if req.Nickname != "" {
		query = query.Where("nickname LIKE ?", "%"+req.Nickname+"%")
	}

	query.Model(&adminModels).Count(&total)
	query.Order("id desc").
		Limit(req.PageNum).
		Offset((req.Page - 1) * req.PageNum).
		Find(&adminModels)

	lastPage := int(math.Ceil(float64(total) / float64(req.PageNum)))
	paging := make([]int, lastPage)
	for i := range paging {
		paging[i] = i + 1
	}

	data, err := app.Trans(adminModels, app.Rule{
		"id":       "||",
		"username": "||",
		"email":    "||",
		"nickname": "||",
		"avatar":   "||" + config.App.Url + "/public/static/images/avatar.png",
	})
	if err != nil {
		return nil, exc.BadRequest(err)
	}

	return res.Ok("admin/system/admin/index", app.Data{
		"breadcrumbs": a.breadcrumbs,
		"resource":    a.resource,
		"filters": []map[string]any{
			{
				"label": "用户名",
				"name":  "username",
				"value": req.Username,
				"type":  "text",
			},
			{
				"label": "邮箱",
				"name":  "email",
				"value": req.Email,
				"type":  "text",
			},
			{
				"label": "昵称",
				"name":  "nickname",
				"value": req.Nickname,
				"type":  "text",
			},
		},
		"pinRow":       true,
		"pinCol":       false,
		"showSelector": false,
		"showCreate":   true,
		"showEdit":     true,
		"showView":     true,
		"showDel":      true,
		"useModal":     true,
		"cols": []map[string]any{
			{
				"label": "用户名",
				"field": "username",
				"type":  "text",
			},
			{
				"label": "昵称",
				"field": "nickname",
				"type":  "text",
			},
			{
				"label": "头像",
				"field": "avatar",
				"type":  "image",
			},
			{
				"label": "邮箱",
				"field": "email",
				"type":  "text",
			},
		},
		"data":        data,
		"total":       total,
		"paging":      paging,
		"currentPage": req.Page,
		"lastPage":    lastPage,
		"prependActions": []map[string]any{
			{
				"type":     "form",
				"formType": "changePassword",
				"title":    "修改密码",
			},
		},
	}), nil
}

// Create 获取添加页面
func (a *AdminController) Create(req *requests.AdminCreateEditRequest) (services.Response, error) {
	return res.Ok("admin/system/admin/form", app.Data{
		"isModal": req.IsModal,
		"breadcrumbs": append(a.breadcrumbs, map[string]any{
			"name": "新增",
			"path": "/admin/system/admin/create",
		}),
		"resource": a.resource,
		"forms": []map[string]any{
			{
				"label":    "用户名",
				"name":     "username",
				"type":     "text",
				"required": true,
			},
			{
				"label":    "密码",
				"name":     "password",
				"type":     "password",
				"required": true,
			},
			{
				"label":    "邮箱",
				"name":     "email",
				"type":     "text",
				"required": true,
			},
			{
				"label": "昵称",
				"name":  "nickname",
				"type":  "text",
			},
			{
				"label": "头像",
				"name":  "avatar",
				"type":  "image",
			},
		},
		"useApi":     true,
		"storeApi":   "adminStore",
		"updateApi":  "adminUpdate",
		"destroyApi": "adminDestroy",
	}), nil
}

// Store 添加数据
func (a *AdminController) Store(req *requests.AdminStoreRequest, admin *models.AdminUser) (services.Response, error) {
	_, err := admin.In(req, app.Rule{
		"_skips": app.Skips{},
		"password": func(req requests.AdminStoreRequest) (string, error) {
			return passwd.Hash(util.SHA256(req.Password))
		},
	})
	if err != nil {
		return nil, exc.BadRequest(err)
	}
	result := db.Create(admin)
	if result.Error != nil {
		return nil, exc.BadRequest(trans.DBError(result.Error))
	}

	return res.SeeOther(a.resource, "创建成功"), nil
}

// Edit 获取修改页面
func (a *AdminController) Edit(req *requests.AdminCreateEditRequest, admin *models.AdminUser) (services.Response, error) {
	var forms []map[string]any
	switch req.FormType {
	case "changePassword":
		forms = []map[string]any{
			{
				"label":    "用户名",
				"name":     "username",
				"type":     "text",
				"value":    admin.Username,
				"disabled": true,
			},
			{
				"label":    "密码",
				"name":     "password",
				"type":     "password",
				"required": true,
			},
		}
	default:
		forms = []map[string]any{
			{
				"label": "用户名",
				"name":  "username",
				"type":  "text",
				"value": admin.Username,
			},
			{
				"label": "邮箱",
				"name":  "email",
				"type":  "text",
				"value": admin.Email,
			},
			{
				"label": "昵称",
				"name":  "nickname",
				"type":  "text",
				"value": admin.Nickname,
			},
			{
				"label": "头像",
				"name":  "avatar",
				"type":  "image",
				"value": admin.Avatar,
				"image": fmt.Sprintf("%s%s", config.App.Url, admin.Avatar),
			},
		}
	}

	return res.Ok("admin/system/admin/form", app.Data{
		"isModal": req.IsModal,
		"breadcrumbs": append(a.breadcrumbs, map[string]any{
			"name": "修改",
			"path": fmt.Sprintf("/admin/system/admin/%s/edit", admin.IDString()),
		}),
		"resource":   a.resource,
		"id":         admin.ID,
		"forms":      forms,
		"useApi":     true,
		"storeApi":   "adminStore",
		"updateApi":  "adminUpdate",
		"destroyApi": "adminDestroy",
	}), nil
}

// Update 修改数据
func (a *AdminController) Update(req *requests.AdminUpdateRequest, admin *models.AdminUser) (services.Response, error) {
	_, err := admin.In(req, app.Rule{
		"username": "||" + *admin.Username,
		"password": func(req requests.AdminUpdateRequest) (string, error) {
			if req.Password != "" {
				return passwd.Hash(util.SHA256(req.Password))
			}
			return admin.Password, nil
		},
		"email":    "||" + *admin.Email,
		"nickname": "||" + *admin.Nickname,
		"avatar":   "||" + *admin.Avatar,
	})
	if err != nil {
		return nil, exc.BadRequest(err)
	}

	result := db.Save(admin)
	if result.Error != nil {
		return nil, exc.BadRequest(result.Error)
	}

	return res.SeeOther(a.resource, "修改成功"), nil
}

// Show 获取详情
func (*AdminController) Show(admin *models.AdminUser) (services.Response, error) {
	return res.Ok("admin/system/admin/index", app.Data{
		"model": admin,
	}), nil
}

// Destroy 销毁数据
func (*AdminController) Destroy(model *models.AdminUser) (services.Response, error) {
	result := db.Delete(model)
	if result.Error != nil {
		return nil, exc.BadRequest(result.Error)
	}

	return res.NoContent("删除成功"), nil
}
